package com.cx.core.magazine.action;

import java.io.File;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.cx.core.magazine.model.bean.Article;
import com.cx.core.magazine.model.bean.form.ArticleForm;
import com.cx.core.magazine.service.MagazineManageService;
import com.cx.core.magazine.util.MagTool;
import com.li.core.actionBase.ActionBase;

/**
 * 李辰晖
 * @author li.chh
 *
 *
 */
public class ArticleManageAction extends ActionBase {
	private File upload;// 上传的文件
	
	public ActionForward addArticle(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ArticleForm articleForm = (ArticleForm)form;
		FormFile upload = articleForm.getUpload();
		String type = upload.getContentType();
		String filename = upload.getFileName();
		byte[] bytes = upload.getFileData();
		InputStream is = upload.getInputStream();
		int size = upload.getFileSize();
		
		System.out.println(size);
		
		Article article = new Article();
		article.setPeriod_id(articleForm.getPeriod_id());
		article.setContent(articleForm.getContent());
		article.setPublish_date(articleForm.getPublish_date_time().getTime());
		article.setPublisher(articleForm.getPublisher());
		article.setTitle(articleForm.getTitle());
		article.setType(articleForm.getType());
		article.setUser("1");
		MagazineManageService ms = (MagazineManageService) super
				.getBean("magazineManageService");
		//ms.saveArticle(article,filename, bytes);
		String imagename = article.getImage_id()+"_"+filename;
		MagTool.getMagTool().saveFileTolocal(imagename,is,true);
		StringBuffer sb = new StringBuffer("{success:true,image_id:'");
		sb.append(imagename);
		sb.append("',id:'");
		sb.append(article.getId());
		sb.append("',publish_date:");
		sb.append(article.getPublish_date());
		sb.append("}");
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(sb.toString());
		return null;
	}
	
	private Article upload(Article article){
		String _imageUrl = null;
		
		
		/*if (upload != null && MyUtils.isValid(getUploadContentType(), getAllowedTypes().split(","))) {
			String rootPath = getSession().getServletContext().getRealPath("/");
			String savePath = rootPath + getSavePath();
			MyUtils.mkDirectory(savePath);
			String newFileName = MyUtils.upload(getUploadFileName(), savePath, getUpload());
			_imageUrl = getSavePath() + newFileName;
			try {
				MyUtils.createMiniPic(new File(savePath + newFileName), maxWidthSize,maxHeightSize);
			} catch (IOException e) {
				e.printStackTrace();
			}
			article.setImageUrl(_imageUrl);
		}*/
		return article;
	}
}
